package cn.yunhe.view;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.document.AbstractXlsView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class ExcleView extends AbstractXlsView{
    //文件名
    private String fileName = null;
    //导出视图自定义接口
    private ExcleExportService excleExportService = null;

    public ExcleView(ExcleExportService excleExportService) {
        this.excleExportService = excleExportService;
    }

    public ExcleView(String fileName, ExcleExportService excleExportService) {
        this.fileName = fileName;
        this.excleExportService = excleExportService;
    }

    @Override
    protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //如果没有自定义接口
        if(excleExportService == null){
            throw new RuntimeException("导出服务接口不能为null");
        }
        //文件名不为空，为空则使用请求路径中的字符串作为文件名
        if(!StringUtils.isEmpty(fileName)){
            String reqCharset = request.getCharacterEncoding();
            reqCharset = reqCharset == null ? "utf-8" : reqCharset;
            fileName = new String(fileName.getBytes(reqCharset),"ISO8859-1");
            //设置文件名
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        }
        //回调接口方法，使用自定义生成Excel文档
        excleExportService.makeWorkBook(model,workbook);
    }


    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public ExcleExportService getExcleExportService() {
        return excleExportService;
    }

    public void setExcleExportService(ExcleExportService excleExportService) {
        this.excleExportService = excleExportService;
    }
}
